package kuang.juc.pc;


//传统版本Synchronized
public class A {
    public static void main(String[] args) {
        Data data = new Data();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.increasement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.decreasement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.increasement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.decreasement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"D").start();
    }

}

//使用while去判断，避免虚假唤醒
//如果用if只判断一次，多条线程去抢就会出现问题
class Data{
    private int number=0;

    public synchronized void increasement() throws InterruptedException {
        //判断等待
        while (number!=0){
            this.wait();
        }
        //业务代码
        number++;
        //通知其它线程
        System.out.println(Thread.currentThread().getName()+"=>"+number);
        this.notifyAll();
    }

    public synchronized void decreasement() throws InterruptedException {
        //判断等待
        while (number==0){
            this.wait();
        }
        //业务代码
        number--;
        System.out.println(Thread.currentThread().getName()+"=>"+number);
        //通知其它线程
        this.notifyAll();
    }
}
